package com.lianxian.xindong.me.mvp.presenter;

import android.annotation.SuppressLint;
import android.app.Application;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.recyclerview.widget.RecyclerView;

import com.hxb.library.integration.AppManager;
import com.hxb.library.di.scope.ActivityScope;
import com.hxb.library.mvp.BasePresenter;
import com.hxb.library.http.imageloader.ImageLoader;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.lianxian.xindong.me.mvp.contract.MyInterestContract;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @作者：hexingbo
 * @时间：07/08/2023
 * @描述：
 */
@ActivityScope
public class MyInterestPresenter extends BasePresenter<MyInterestContract.Model, MyInterestContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public MyInterestPresenter(MyInterestContract.Model model, MyInterestContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.mDatas = null;
        this.mAdapter = null;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate() {
        requestDatas(true);//打开 App 时自动加载列表
    }

    @Inject
    List<Object> mDatas;
    @Inject
    RecyclerView.Adapter mAdapter;

    private int pageCurrent = 0;
    private int preEndIndex;
    /**
     * 总数据大小
     */
    private int mTotalSize = 0;

    /**
     * 是否还有更多数据
     *
     * @return
     */
    public boolean hasLoadedAllItems() {
        return !(mTotalSize > mDatas.size());
    }

    @SuppressLint("CheckResult")
    public void requestDatas(boolean pullToRefresh) {
        if (pullToRefresh) {
            mTotalSize = 0;
            pageCurrent = 1;//下拉刷新默认只请求第一页
            mDatas.clear();
            mAdapter.notifyDataSetChanged();
        }

        Observable.timer(3, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (pullToRefresh)
                            mRootView.hideLoading();//隐藏下拉刷新的进度条
                        else {
                            mRootView.endLoadMore();//隐藏上拉加载更多的进度条
                        }
                        mTotalSize = 20;
                        if (mDatas.size() >= mTotalSize) {
                            return;
                        }
                        List<Object> records = new ArrayList<>();
                        for (int i = 0; i < 10; i++) {
                            records.add(new Object());
                        }
                        if (records == null || records.size() == 0) return;
                        pageCurrent = pageCurrent + 1;
                        if (pullToRefresh) mDatas.clear();//如果是下拉刷新则清空列表
                        preEndIndex = mDatas.size();//更新之前列表总长度,用于确定加载更多的起始位置
                        mDatas.addAll(records);
                        if (pullToRefresh)
                            mAdapter.notifyDataSetChanged();
                        else
                            mAdapter.notifyItemRangeInserted(preEndIndex, records.size());
                    }
                });
//        mModel.getNetForData(pageCurrent, 10)
//                .subscribeOn(Schedulers.io())
//                .retryWhen(new RetryWithDelay(0, 0))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
//                .doOnSubscribe(disposable -> {
//                    if (pullToRefresh)
//                        mRootView.showLoading();//显示下拉刷新的进度条
//                    else
//                        mRootView.startLoadMore();//显示上拉加载更多的进度条
//                }).subscribeOn(AndroidSchedulers.mainThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doFinally(() -> {
//                    if (pullToRefresh)
//                        mRootView.hideLoading();//隐藏下拉刷新的进度条
//                    else
//                        mRootView.endLoadMore();//隐藏上拉加载更多的进度条
//                })
//                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
//                .subscribe(new MyHttpResultObserver<ResultBaseListBean<Object>>(mErrorHandler) {
//
//                    @Override
//                    public void onResult(ResultBaseListBean<Object> result) {
//                        if (result == null) {
//                            return;
//                        }
//                        mTotalSize = result.getTotal();
//                        List<Object> records = result.getRecords();
//                        if (records == null || records.size() == 0) return;
//                        pageCurrent = pageCurrent + 1;
//                        if (pullToRefresh) mDatas.clear();//如果是下拉刷新则清空列表
//                        preEndIndex = mDatas.size();//更新之前列表总长度,用于确定加载更多的起始位置
//                        mDatas.addAll(records);
//                        if (pullToRefresh)
//                            mAdapter.notifyDataSetChanged();
//                        else
//                            mAdapter.notifyItemRangeInserted(preEndIndex, records.size());
//                    }
//                });
    }
}

